package com.uiao.stone.common.interceptor;

import com.uiao.stone.AuthInterceptor;
import com.uiao.stone.common.resolver.CurrentUserArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * 适配器  要加上@Configuration才可以起作用
 * Created by Administrator on 2017/9/20.
 */
@Configuration
public class MyWebMvcConfigureAdapter extends WebMvcConfigurerAdapter {

    /**
     * 配置静态资源，除了在application里配置外可以继承WebMvcConfigurerAdapter來配置
     * addResourceHandler 为映射路径；addResourceLocations为文件路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/personResource/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

    /**
     * 页面跳转，用于进入首页是的页面
     * 用了application的thymeleaf配置，定位到某个文件，不是目录
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/").setViewName("home");
        super.addViewControllers(registry);
    }

    /**
     * 添加拦截器
     * 拦截器在addViewControllers前执行，所以要把首页url和登陆url移除，但是配置了静态资源的url不会拦截，配置了addViewControllers的也会拦截，所以要排除一下
     * 优先级为：静态资源 > 拦截器exclude > 拦截器pattern > 页面跳转（addViewControllers）
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/**") // 这些会被拦截
                .excludePathPatterns("/", "/login", "/login/prelogin", "/login/dologin", "/usermanager/**"); // 这些不会拦截
        super.addInterceptors(registry);
    }

    /**
     * 添加自定义的参数注解
     *
     * @param argumentResolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CurrentUserArgumentResolver());
    }
}
